import React, { useState, useRef, useEffect, useMemo } from 'react'
import { useNavigate, NavLink } from 'react-router-dom'
import { Button, Toast, Popup, Cascader, Form, Input } from 'antd-mobile'
import { LeftOutline, RightOutline, EnvironmentOutline } from 'antd-mobile-icons'
import './address.scss'
import API from '../../api/address'
import { IAddress } from '../../../interface'
import { store } from '../../../store'
import { cityData, longOptions } from '../../pushAddress/city'

interface Icity {
  value: number;
  label: string;
  children: {
    value: number;
    label: string;
    children: {
      value: number;
      label: string;
    }
  }
}

const initItem = {
  address_city: '',
  address_contacts: '',
  address_phone: '',
  address_town: '',
  _id: '',
  user_id: ''
}

export default function Address() {
  const navigate = useNavigate()
  const { token } = store.getState().userReducer.user
  const [address, setAddress] = useState<IAddress[]>([])
  const getAddress = async () => {
    let res = await API['getAddress']({ token })
    console.log(res, '获取地址')
    setAddress(res.data.data)
  }

  const [visible1, setVisible1] = useState(false)
  const [visible, setVisible] = useState(false)
  const [val, setVal] = useState<string>('省/市/区')


  const [value, setValue] = useState<string[]>([])
  const [item, setItem] = useState<IAddress>(initItem)
  const [city, setCity] = useState<any>(cityData.map((item: any) => {
    item.value = item.label
    return item
  }))
  useEffect(() => {
    getAddress()
  }, [])
  const onFinish = (async (values: any) => {
    console.log(val.split('-').join(""), 'form')
    // console.log(values)
    let res = await API['addressEdit']({ token, id: item._id, address_city: val.split('-').join(""), address_town: values.address_town, address_contacts: values.address_contacts, address_phone: values.address_phone })
    console.log(res, '修改地址')
    setTimeout(() => {
      Toast.show({
        content: '地址已修改',
        position: 'top'
      })
      setItem(initItem)
      setVisible(false)
      getAddress()
    }, 1000)
  })

  const addressDel = async (items: IAddress) => {
    let res = await API['addressDel']({ token, id: items._id })
    console.log(res, '删除地址')
    Toast.show({
      content: '地址已删除',
      position: 'top'
    })
    getAddress()
  }

  useMemo(() => {
    console.log(val,"val改变")
    return val

  }, [val])

  return (
    <div>
      <div className='address_back'>
        <Button onClick={() => navigate(-1)}><LeftOutline /></Button>
        选择收货地址
        <aside onClick={() => navigate('/pushAddress')}>新增地址</aside>
      </div>
      <div className='address_main'>
        {
          address.length ? address.map((item: IAddress) => <div key={item._id}>
            <div className='location'>
              <article onClick={() => {
                setVisible(true)
                setItem(item)
                console.log(item)
              }}>
                <i><EnvironmentOutline /></i>
                <h2>{item.address_city} {item.address_town}</h2>
              </article>
              <aside>{item.address_contacts} {item.address_phone}</aside>
              <b><RightOutline /></b>
              <Button color='danger' size='mini' onClick={() => addressDel(item)}>删除</Button>
            </div>
          </div>) : <div className='noAddress' key={item._id}>
            <i><EnvironmentOutline /></i>
            <h1>还没有任何配送地址</h1>
            <div className='address_go' onClick={() => {
              navigate('/pushAddress')
            }}>新增地址</div>
          </div>
        }
      </div>
      <div className='pushAddress_main'>
        <div className='Cascader'>
          <Cascader
            options={city}
            visible={visible1}
            onClose={() => {
              setVisible1(false)
            }}
            value={value}
            onConfirm={setValue}
            onSelect={(val, extend) => {
              console.log('onSelect', val, extend.items)
            }}
          >
            {items => {
              if (items.every(item => item === null)) {
                return '省/市/区'
              } else {
                setVal(items.map(item => item?.label ?? '未选择').join('-'))
                return items.map(item => item?.label ?? '未选择').join('-')
              }
            }}
          </Cascader>
        </div>
        <Popup
          visible={visible}
          onMaskClick={() => {
            setItem(initItem)
            setVisible(false)
          }}
          position='right'
          bodyStyle={{ width: '60vw' }}
        >
          <Form layout='vertical' initialValues={item} onFinish={onFinish} footer={
            <Button block type='submit' color='primary' size='large'>
              修改
            </Button>
          }>
            <Form.Item label='收货地址' name='address_city' onClick={() => {
              setVisible1(true)
            }}>
              {
                val
              }
            </Form.Item>

            <Form.Item label='门牌号' name='address_town'>
              <Input placeholder='楼号/门牌号、如A座101室' clearable />
            </Form.Item>
            <Form.Item label='联系人' name='address_contacts'>
              <Input placeholder='您的名字' clearable />
            </Form.Item>
            <Form.Item label='手机号' name='address_phone'>
              <Input placeholder='配送员联系您的手机号' clearable />
            </Form.Item>
          </Form>
        </Popup>
      </div>

    </div>
  )
}
